<?php
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Response as FacadesResponse;
use \Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class CommentController extends CenterController {

	protected $layout = 'layouts.master';

	/**
	 * 获取经过验证的Comment
	 */
	public function getComment($id)
	{
		$comment = Comment::find($id);
		
		if (!$comment) {
			return $this->makeView(
                'errors.400', 
                '该评论不存在',
                400
            );
		}

		if($comment->creator_id != Auth::user()->id)
		{	
			return $this->makeView(
				'errors.403',
				'你没有权限操作这个评论',
				403
			);
		}

		return $comment;
	}

	/*
	 * 删除回复
	 */
	public function remove($id)
	{
		$comment = $this->getComment($id);
		if (get_class($comment) != 'Comment') {
			return $comment;
		}

		try{
			$comment->delete();
			return $this->makeView(
				'general.201',
				'成功删除评论',
				200
			);
		} catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
				'errors.503', 
				'删除评论失败，请稍后再试。',
				503
			);
		}
	}


	/**
	 * 创建评论
	 * 
	 * TODOs
	 * - send out notification to mobiles (could be offline)
	 */
	public function comment($id)
	{
		$question = $this->getQuestion($id);
		if (!is_a($question, 'Post')) {
		    return $question;
		}

		// validations
		$rules = array (
			'comment' => 'required',
			'creator_id' => 'required|exists:user,id',
		);
		$messages = array(
			'comment.required' => '请输入评论内容',
			'creator_id.required' => '请提交创建评论的用户',
			'creator_id.exists' => '找不到和这个id对应的用户',
		);

		$posts = Input::all();
		$validator = Validator::make ( $posts, $rules, $messages );
		if ($validator->fails()) {
			// the given data did not pass validation
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
		}

		if (!$question->canReply($posts['creator_id'])) {
			// 403
            return $this->makeView(
                'errors.403', 
                '这个用户没有权限对这个咨询进行回复或者评论',
                403
            );
		}

		try {
			$posts = UtilsHelper::filter_sensitive_word($posts);
	        $comment = new Comment();
	        $comment->content = $posts['comment'];
	        $comment->creator_id = $posts['creator_id'];
	        $question->save_comment( $comment );
	        if($question->creator_id == 0){
	        	$question->status == POST::STATUS_WAIT_FOR_CONFIRM;
	        }
	        $question->save();

	        // 如果创建评论的不是咨询者本人，则把status设置为replied
	        $question_creator = User::find($question->creator_id);
	        $question_commentator = $question->commentators()->first();

	        	// 如果是提问者回复，则发送给律师
	        if (($question->creator_id == $posts['creator_id']) && $question_commentator) {
         		// 给相关的律师提示
         		$site_lawyer_conf = Config::get('site.notify_lawyers');
	            if (isset($site_lawyer_conf[$question->post_category . ''])  && ! Config::get('app.debug')){
	                $lawyer_uids = $site_lawyer_conf[$question->post_category . '' ];
	                $snsmembers = User::whereIn('id',$lawyer_uids)->get();
	                //发送微信消息给律师
	                foreach($snsmembers as $snsmember){
	                    if($snsmember->wx_openid ){							
	                        MsgHelper::sendReplyToPostCreator(
	                        	$snsmember->wx_openid,
	                        	$comment->creatorName(),
	                        	$comment->content,
	                        	$question
	                        );
	                        Log::info('send to question commentator: ' . $snsmember->wx_openid . " - snsmember id: " . $snsmember->id . " - comment creator: " . $comment->creatorName() . " - " . $comment->content . " - " . $question->id);
	                    }
	                }
	            }
	        } else if (($question->creator_id != $posts['creator_id']) && $question_creator->wx_openid && ! Config::get('app.debug')) {
	        	// 如果是律师回复，则发送给提问者
				MsgHelper::sendReplyToPostCreator(
					$question_creator->wx_openid,
					$comment->creatorName(),
                	$comment->content,
                	$question
				);

				// 同时发送给回答的律师，这样我们知道用户收到了什么消息
         		$site_lawyer_conf = Config::get('site.notify_lawyers');
	            if ($site_lawyer_conf[$question->post_category . ''] ){
	                $lawyer_uids = $site_lawyer_conf[$question->post_category . '' ];
	                $snsmembers = User::whereIn('id',$lawyer_uids)->get();
	                //发送微信消息给律师
	                foreach($snsmembers as $snsmember){
	                    if($snsmember->wx_openid ) {				
							MsgHelper::sendReplyToPostCreator(
	                        	$snsmember->wx_openid,
								$comment->creatorName(),
			                	$comment->content,
			                	$question
							);
	                        Log::info('question commentator: ' . $snsmember->wx_openid . " - " . $comment->creatorName() . " - " . $comment->content . " - " . $question->id);
	                    }
	                }
	            }
	        	Log::info('send to question creator: ' . $question_creator->wx_openid . " - creator id: " . $question_creator->id . " - comment creator: " . $comment->creatorName() . " - " . $comment->content . " - " . $question->id);
			}

//	        UserScoresHistory::comment();
			if ($question->post_type == Post::TYPE_PAY_TEXT || $question->post_type == Post::TYPE_PAY_COMPANY) {
				//付费咨询(环信)
				Event::fire('pay_post_reply', [$comment,$question]);
			}else{
				//免费咨询
				Event::fire('free_post_reply', [$comment,$question]);
			}

		} catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
				'errors.503', 
				'咨询律师失败，请稍后再试。',
				503
			);
		}

		$comment->load('owner');
		$commentArr = $comment->toArray();
		$commentArr['creator_name'] = $commentArr['owner']['realname'];
		$commentArr['creator_avatar'] = UtilsHelper::getImage($commentArr['owner']['avatar'], "img/dfimg.png");
		$commentArr['from_creator'] = (bool)($commentArr['owner']['id'] == $question['creator_id']);
		unset($commentArr['owner']);
		
        return $this->makeView(
            'general.201', 
            $commentArr,
            201
        );
	}		
	
	/**
	 * 获取问题，如果出错了，会返回合适的Response
	 * 
	 * @param integer $id
	 */
	protected function getQuestion($id) {
		try {
			$post = Post::findOrFail($id);
		} catch(ModelNotFoundException $e) {
			return $this->makeView(
				'errors.404',
				'没有找到符合要求的纪录。',
				404
			);
		} catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView(
				'errors.503', 
				'咨询律师失败，请稍后再试。',
				503
			);
		}
		return $post;
	}
	
	/**
	 * 获取评论列表
	 * @param post_id $post_id
	 */
	public function commentList($post_id){
		$post = $this->getQuestion($post_id);
		$page = Input::get('page', 1);
		$row_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
		$offset = ($page-1)*$row_per_page;
		$data = [];
		$data['comments'] = $post->getComments($row_per_page, $offset);
		return $this->makeView('general.200', $data);
	}
}
